//
// Created by czm on 2023/12/21.
//

#include <string.h>
#include <stdlib.h>

/* BLE */
#include "esp_nimble_hci.h"
#include "nimble/nimble_port.h"
#include "nimble/nimble_port_freertos.h"
#include "host/ble_hs.h"
#include "host/util/util.h"
#include "console/console.h"
#include "services/gap/ble_svc_gap.h"
#include "esp_log.h"

#include "../global.h"

#include "CardUtils.h"

#define TAG "CardUtils"

CardUtils::CardUtils() {

}

CardUtils::~CardUtils() {

}

void CardUtils::addCard(char *szCard) {
    mutex.lock();
    bool founded = false;
    for(auto* pItem : cardList){
        if(strcmp(pItem->szCard,szCard)==0){
            founded = true;
            break;
        }
    }
    if(!founded){
        CardInfo* pItem = new CardInfo();
        pItem->szCard = (char*)malloc(strlen(szCard)+1);
        strcpy(pItem->szCard,szCard);
        pItem->isSend = false;
        cardList.push_back(pItem);
    }
    mutex.unlock();
}

void CardUtils::reset() {
    mutex.lock();
    for (auto* pItem : cardList){
        free(pItem->szCard);
        delete pItem;
    }
    cardList.clear();
    mutex.unlock();
}

void CardUtils::notifyCard() {
    if(mutex.try_lock()){
        for(auto* pItem : cardList){
            if(!pItem->isSend){
                struct os_mbuf *om = ble_hs_mbuf_from_flat(pItem->szCard, strlen(pItem->szCard));
                int rc = ble_gattc_notify_custom(g_conn_handle, g_card_notify_handle, om);
                if(rc == 0) {
                    ESP_LOGI(TAG, "notify rc=%d card=%s", rc, pItem->szCard);
                    pItem->isSend = true;
                }
                break;
            }
        }
        mutex.unlock();
    }
}